<?php

App::import('Vendor', 'twitter', array('file' => 'twitter' . DS . 'TwitterApi.php'));

/**
 * Function converts an Javascript escaped string back into a string with specified charset (default is UTF-8). 
 * Modified function from http://pure-essence.net/stuff/code/utf8RawUrlDecode.phps
 *
 * @param string $source escaped with Javascript's escape() function
 * @param string $iconv_to destination character set will be used as second paramether in the iconv function. Default is UTF-8.
 * @return string 
 */
function unescape($source, $iconv_to = 'UTF-8') {
  $decodedStr = '';
  $pos = 0;
  $len = strlen ($source);
  while ($pos < $len) {
      $charAt = substr ($source, $pos, 1);
      if ($charAt == '%') {
          $pos++;
          $charAt = substr ($source, $pos, 1);
          if ($charAt == 'u') {
              // we got a unicode character
              $pos++;
              $unicodeHexVal = substr ($source, $pos, 4);
              $unicode = hexdec ($unicodeHexVal);
              $decodedStr .= code2utf($unicode);
              $pos += 4;
          }
          else {
              // we have an escaped ascii character
              $hexVal = substr ($source, $pos, 2);
              $decodedStr .= chr (hexdec ($hexVal));
              $pos += 2;
          }
      }
      else {
          $decodedStr .= $charAt;
          $pos++;
      }
  }

  if ($iconv_to != "UTF-8") {
      $decodedStr = iconv("UTF-8", $iconv_to, $decodedStr);
  }
  
  return $decodedStr;
}

/**
 * Function coverts number of utf char into that character.
 * Function taken from: http://sk2.php.net/manual/en/function.utf8-encode.php#49336
 *
 * @param int $num
 * @return utf8char
 */
function code2utf($num){
  if($num<128)return chr($num);
  if($num<2048)return chr(($num>>6)+192).chr(($num&63)+128);
  if($num<65536)return chr(($num>>12)+224).chr((($num>>6)&63)+128).chr(($num&63)+128);
  if($num<2097152)return chr(($num>>18)+240).chr((($num>>12)&63)+128).chr((($num>>6)&63)+128) .chr(($num&63)+128);
  return '';
}

class StatusesController extends AppController {
	var $name = 'Statuses';
	var $helpers = array('javascript', 'form', 'html');
	var $uses = array('Location', 'Address', 'Status', 'School', 'Favorite', 'User', 'Category');
	var $components = array('Session', 'RequestHandler', 'Twitter', 'Fauth');
	var $consumer_key = "si2UvZAvFqJULHPSReXjA";
	var $consumer_secret = "qn4YEDOFUPYTwWkexlk2SdDYcW7zAvRaPNSR5GJ5k";
	var $datahash = array();
	var $twitter;
	var $twitterUser;
	var $user;
	var $theme = "jquery-mobile";

	function beforeFilter() {

		$this->datahash['twitter_user'] = $this->Session->read('twitter_user');

		// セッションまたはクッキーにユーザーIDがあるとき
		if ($this->Fauth->isAuth()) {
			$this->datahash['login_user'] = $this->Fauth->user();
		}
		// セッションまたはクッキーにユーザーIDがないとき
		else {
			if (!$this->Fauth->isAllowAction()) {
				if ($this->Fauth->canmove()) {
					$this->redirect('../users/login/');
				}
			}
		}
		//Ajaxの共通処理
		//アクションにajaxが入っていたら実行
		if ($this->RequestHandler->isAjax() && strstr($this->action, 'ajax')) {
			//jquery-mobileはすべてajaxなので例外も入れてやる
			Configure::write('debug', 0);
			$this->layout = "";
			$this->autoRender = false;
			$this->RequestHandler->setContent('json');
			$this->RequestHandler->respondAs('application/json; charset=UTF-8');
		}
	}

	function beforeRender() {
		$this->set('datahash', $this->datahash);
		parent::beforeRender();
	}

	function index() {
		echo "index";
		exit();
	}

	function contents() {
		$this->layout = "default";

	}

	function _setFavData($values, $userId) {
		$data = $this->Favorite->findAllByUserId($userId);
		$temp = array();
		foreach ($values as $key => $val) {
			foreach ($data as $index => $obj) {
				if (strval($obj['Favorite']['status_id']) === strval($values[$key]['Status']['id'])) {
					$values[$key]['Favorite'] = $obj['Favorite'];
					unset($data[$index]);
					break;
				}
			}
			if (empty($values[$key]['Favorite']))
				$values[$key]['Favorite'] = null;
		}
		return $values;
	}

	function del($id = null) {
		if ($id != null) {
			if ($this->Status->delete($id)) {
				$this->Session->setFlash("削除しました");
				$this->redirect('../users/index/');
			} else {
				$this->Session->setFlash("削除に失敗しました");
				$this->redirect('../users/index/');
			}
		} else {
			$this->redirect('../users/index/');
		}
	}

	/*
	 * 投稿内容を追加する
	 */
	function add() {
		$this->layout = "dialog";
		$this->set('title_for_layout', "今何してる？");
		// カテゴリ一覧の取得
		$categoryData = $this->Category->find("all");
		$category = array();
		foreach ($categoryData as $key => $val) {
			$category[$val['Category']['id']] = $val['Category']['name'];
		}
		$this->datahash['category'] = $category;
	}

	/* 返信
	 * テストです
	 * */
	function reply($to) {
		$this->layout = "dialog";
		//$_GET['quote'] = unicode_encode($_GET['quote']);
		if ($_GET['quote'] != "" && isset($_GET['quote'])) {
			$title = '引用して返信';
		} else {
			$title = '返信';
		}
		// カテゴリ一覧の取得
		$categoryData = $this->Category->find("all");
		$category = array();
		foreach ($categoryData as $key => $val) {
			$category[$val['Category']['id']] = $val['Category']['name'];
		}
		$this->datahash['category'] = $category;
		$this->set('title_for_layout', $title);
	}

	/*-------------------------------以下はAjax専用関数-------------------------------*/
	function ajax_removeStatus(){
		header("Content-Type: text/javascript; charset=utf-8");
		if ($this->params['form']['status_id']) {
			$twitterApi = new TwitterApi($this->consumer_key, $this->consumer_secret, $this->datahash['login_user']['User']['access_token_key'], $this->datahash['login_user']['User']['access_token_secret']);
			$response = $twitterApi->removeTweet($this->params['form']['status_id']);
			if($response->id_str != null){
				$this->Status->delete($this->params['form']['status_id']);
			}
			echo json_encode($response);
			exit();
		}else{
			echo json_encode(array("error" => "1"));
			exit();
		}
	}
	
	function ajax_addStatus() {
		$values = array();
		if (!empty($this->data['Status']['text'])) {
			$status = $this->data['Status'];
			$user = $this->User->findById($status['user_id']);
			// #frexiをつけるか
			if($user['User']['use_frexi_tag'] == 0){
				$text = $status['text'];
			} else {
				$text = $status['text'] . " #frexi";
			}
			
			// 位置情報をつけるか
			if ( $user['User']['use_location_information'] == 1 && 
				 !empty($status['lat']) && !empty($status['lng'])) {
				//TwitterApiの作成

				$this->Address->saveByLocation($status['lat'], $status['lng']);
				$location = array('address_id' => $this->Address->getID(), 'lat' => $status['lat'], 'lng' => $status['lng']);
				$this->Location->create();
				$this->Location->save($location);
				$status['location_id'] = $this->Location->getID();
				$params = array('status' => $text, 'lat' => $location['lat'], 'long' => $location['lng']);
			} else {
				$params = array('status' => $text);
			}
			$twitterApi = new TwitterApi($this->consumer_key, $this->consumer_secret, $this->datahash['login_user']['User']['access_token_key'], $this->datahash['login_user']['User']['access_token_secret']);

			$response = $twitterApi->postUpdate($params);
			//twitterにデータ保存

			$status['id'] = $response->id_str;
			$status['source'] = $response->source;
			$status['created_at'] = $response->created_at;
			//TwitterのStatusID
			if (!empty($response->id_str) && $this ->Status->save($status)) {
				$values = array("msg" => $text . "を送信しました");
			} else {
				$values = array("msg" => "投稿に失敗しました");
			}
		} else {
			$values = array("msg" => "投稿に失敗しました");
		}
		header("Content-Type: text/javascript; charset=utf-8");
		echo json_encode($values);
		exit();
	}

	/*
	 * getMyStatusesのサーバー側
	 */
	function ajax_searchStatuses() {
		if ($this->params['form']['word']) {
			$this->Status->recursive = 2;
			//アドレスもくっつける
			$offset = empty($this->params['form']['offset']) ? 0 : $this->params['form']['offset'];
			$count = empty($this->params['form']['count']) ? 10 : $this->params['form']['count'];
			$category_id = empty($this->params['form']['category_id']) ? 0 : $this->params['form']['category_id'];

			$words = explode(" ", $this->params['form']['word']);
			$values = $this->Status->search($words, $category_id, $offset, $count);
			//Twitterの情報も付加
			foreach ($values as $key => $val) {
				if (!empty($val['User']['name'])) {
					$values[$key]['TwitterUser'] = $this->Twitter->getTwitterUser($val);
				}
			}
			$values = $this->_setFavData($values, $this->datahash['login_user']['User']['id']);
		} else {
			$values = array('Error' => '1');
		}
		header("Content-Type: text/javascript; charset=utf-8");
		echo json_encode($values);
		exit();
	}

	/*
	 * getMyStatusesのサーバー側
	 */
	function ajax_getMyStatuses() {
		///sleep(1);	//ダミー遅くすればそれっぽく見える

		$this->Status->recursive = 2;
		//アドレスもくっつける
		$statusId = empty($this->params['form']['statusId']) ? 0 : $this->params['form']['statusId'];
		$count = empty($this->params['form']['count']) ? 10 : $this->params['form']['count'];
		if (!empty($user)) {
			$values = $this->Status->findAllByUserId($user['User']['id'], $statusId, $count);
			foreach ($values as $key => $val) {
				$values[$key]['TwitterUser'] = $this->datahash['twitter_user'];
			}
		} else {
			$values = array('Error' => '1');
		}
		header("Content-Type: text/javascript; charset=utf-8");
		echo json_encode($values);
		exit();
	}

	/*
	 * getNeighborsのサーバー側
	 */
	function ajax_getNeighbors() {
		if ($this->params['form']['north'] != null && $this->params['form']['east'] != null && $this->params['form']['south'] != null && $this->params['form']['west'] != null) {
			/*
			 $this->Location->recursive = 2;	//アドレスもくっつける

			 $this->User->unbindModel(
			 array(
			 'hasMany' => array('Status')
			 ),
			 false
			 );*/
			$this->Status->recursive = 2;
			//アドレス、キャンバスもくっつける
			$north = $this->params['form']['north'];
			$east = $this->params['form']['east'];
			$south = $this->params['form']['south'];
			$west = $this->params['form']['west'];
			$values = $this->Status->findNeighborInMap($north, $east, $south, $west);
			// 地図の領域内のツイートをとってくる
			$twitterApi = new TwitterApi($this->consumer_key, $this->consumer_secret, $this->datahash['login_user']['User']['access_token_key'], $this->datahash['login_user']['User']['access_token_secret']);
			//Twitterの情報も付加
			foreach ($values as $key => $val) {
				if (!empty($val['User']['name'])) {
					$values[$key]['TwitterUser'] = $this->Twitter->getTwitterUser($val);
				}
			}
			$values = $this->_setFavData($values, $this->datahash['login_user']['User']['id']);
		} else {
			$values = array('Error' => '1');
		}
		header("Content-Type: text/javascript; charset=utf-8"); 
		echo json_encode($values);
		exit();
	}

	/*
	 * getStatusesBySchoolIdのサーバー側
	 */
	function ajax_getStatusesBySchoolId() {
		if (!empty($this->params['form']['schoolId'])) {
			$values = array();
			$this->Status->recursive = 2;
			//アドレス、キャンバスもくっつける
			$statusId = empty($this->params['form']['statusId']) ? 0 : $this->params['form']['statusId'];
			$count = empty($this->params['form']['count']) ? 10 : $this->params['form']['count'];
			$school = $this->School->findById($this->params['form']['schoolId']);

			foreach ($school['Campus'] as $key => $val) {
				//amはarray_mergeの省略形
				$values = am($values, $this->Status->findByCampusId($val['id'], $statusId, $count));
			}
			
			//Twitterの情報も付加

			foreach ($values as $key => $val) {
				if (!empty($val['User']['name'])) {
					$values[$key]['TwitterUser'] = $this->Twitter->getTwitterUser($val);
				}
			}
			$values = $this->_setFavData($values, $this->datahash['login_user']['User']['id']);
			
		} else {
			$values = array('Error' => 1);
		}
		header("Content-Type: text/javascript; charset=utf-8"); 
		echo json_encode($values);
		exit();
	}

	function ajax_uploadFile(){
		//console.log("uploadFile");
		//echo json_encode($this->data);
		//exit();		
		$result = true;
		if (!$this->data['Status']['upload_file']) {
			//$this >set('error', 'アップロードするファイルを選択してください');
			//$this->render('upload', 'ajax');
		} else {
			if ($this->data['Status']['upload_file']['type'] != 'image/png') {
				$this->set('error', 'アップロードできる画像は JPEG のみです');
				//$this->render('upload', 'ajax');
			} else {
				$filename = '/files/' . intval(rand()) . '.jpg';
				$result = @move_uploaded_file($this->data['Status']['upload_file']['tmp_name'], "C:\tmp\test.png");
				//$this->set('filename', $filename);
				//$this->render('upload', 'ajax');
				if($result != true){
					$result = false;
				}
			}
		}
		header("Content-Type: text/javascript; charset=utf-8"); 
		echo json_encode(array("test" => $_FILES));
		exit();	

	}

}
?>